package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.product.client.common.constant.RedisConst;
import com.atguigu.gmall.product.client.common.result.Result;
import com.atguigu.gmall.product.client.common.util.AuthContextHolder;
import com.atguigu.gmall.product.client.model.user.UserAddress;
import com.atguigu.gmall.product.client.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //用户登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        UserInfo userInfo1=userService.login(userInfo);
        if (userInfo1 != null){
            Map map = new HashMap();  //不给类型  会影响编译期java.class文件  不会影响运行期
            //token UUID 36位长度的字符串 去掉4个- 还剩下32个长度的字符串
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //设置token
            map.put("token",uuid);
            //设置用户昵称
            map.put("nickName",userInfo1.getNickName());
            //缓存
            redisTemplate.opsForValue().set(uuid,userInfo1.getId().toString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        }else{
            //登录失败
            return Result.fail().message("您输入的用户名或密码不正确");
        }
    }


    /**
     * 退出登录
     * @param request
     * @return
     */
    @GetMapping("logout")
    public Result logout(HttpServletRequest request){
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX + request.getHeader("token"));
        return Result.ok();
    }

/*    //根据用户Id查询收获地址集合
    @GetMapping("/userAddressList")
    public List<UserAddress> userAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userService.userAddressList(userId);
    }*/

    //根据用户ID查询收货地址集合
    @GetMapping("/userAddressList")
    public List<UserAddress> userAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userService.userAddressList(userId);
    }


}
